package com.atgouwu.mall.sso.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 单点登录
 */
@RestController
@RequestMapping("sso/login")
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //根据token从redis获取用户信息
    @ResponseBody
    @GetMapping("/userinfo")
    public String userinfo(@RequestParam(value = "token") String token) {
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    //sso登录页
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) { //从sso的cookie获取token
            return "redirect:" + url + "?token=" + sso_token; //有就携带token返回原服务
        }
        model.addAttribute("url", url);
        return "login"; //没有就账号密码登录
    }

    //sso输入账号密码登录
    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("redirect_url") String url, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            String uuid = UUID.randomUUID().toString().replace("_", "");
            redisTemplate.opsForValue().set(uuid, username); //用户信息存入redis
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token); //token存入sso的cookie
            return "redirect:" + url + "?token=" + uuid; //登录成功携带token重定向到原服务
        }
        return "login";
    }

}
